package com.bjtu.boatmq.broker.service;

import com.bjtu.boatmq.broker.config.BrokerConfig;
import com.bjtu.boatmq.broker.service.outer.Broker2RouterService;
import com.bjtu.boatmq.broker.service.outer.BrokerLogger;
import com.bjtu.boatmq.broker.service.processor.ProcessorService;
import com.bjtu.boatmq.broker.service.processor.ProcessorServiceImpl;

public class BrokerService {
    private BrokerConfig brokerConfig = null;
    private ProcessorService processorService = null;  // 处理器服务
    private Broker2RouterService broker2RouterService; // 与router交互服务


    public BrokerService(BrokerConfig brokerConfig){
        System.out.println("进入BrokerService()");
        this.brokerConfig = brokerConfig;
        processorService = new ProcessorServiceImpl();
        broker2RouterService = new Broker2RouterService();
    }

    public void start() throws Exception{
        // 1.注册节点
        if(broker2RouterService.registerBroker()){
            BrokerLogger.writeInfo("broker节点注册成功");
        }else{
            BrokerLogger.write("10000","broker节点注册失败");
            return;
        }
        // 2.开启处理器服务
        if(processorService.initialize()){
            processorService.start();
        }
        // 启动成功，获取本机地址和监听端口，并打印出来
        BrokerLogger.writeInfo( "[" +
                BrokerConfig.getBrokerName() +
                " " +
                BrokerConfig.getBrokerHost() +
                ":" +
                BrokerConfig.getBrokerPort() +
                "]" +
                " start successful!");
    }

    public void shutdown() throws Exception{
        // 关闭处理器服务
        processorService.shutdown();
        // 关闭router
        broker2RouterService.shutdown();
    }
}
